package com.test.netty.nettyhb;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class HeartBeatInitializer extends ChannelInitializer<Channel> {

    @Override
    protected void initChannel(Channel ch) throws Exception {
        initProtobuffHb(ch);
    }


    private void initHeartbeat(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast(new IdleStateHandler(Const.READER_IDLE_TIME, Const.WRITER_IDLE_TIME, Const.ALL_IDLE_TIME, Const.TIME_UNIT));
        pipeline.addLast(new HeartBeatHandler());
        pipeline.addLast(new BizHandler());
    }

    private void initProtobuffHb(Channel ch)throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(CProtocol.Message.getDefaultInstance()));
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(new IdleStateHandler(Const.READER_IDLE_TIME, Const.WRITER_IDLE_TIME, Const.ALL_IDLE_TIME, Const.TIME_UNIT));
        pipeline.addLast(new MessageHandler());
        pipeline.addLast(new ProtobuffBizHandler());
    }
}
